<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800"
      draggable
      @close="closeDialog"
      destroy-on-close
    >
      <el-descriptions
        class="margin-top"
        title=""
        :column="3"
        border
        v-show="props.isReadonly"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">工序</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.processCode ?? "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">生产线</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.processEquipCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.equipName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.alarmName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警等级</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{
              dictionaryStore.filterDictName(
                "ScaAlarmLevel",
                formData.alarmLevel
              )
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">参数名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.parameterDesc }}
          </div>
        </el-descriptions-item>
        <!-- <el-descriptions-item>
          <template #label>
            <div class="cell-item">参数值</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.parameterValue }}
          </div>
        </el-descriptions-item> -->
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">触发条件</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <!-- {{ formData.alarmTriggerConditions ?? "" }} -->
            {{ conditionValue.join(",") }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">生成工单</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <el-tag v-show="formData.isOrder == 1" type="success">是</el-tag>
            <el-tag v-show="formData.isOrder != 1" type="info">否</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">发送邮件</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <el-tag v-show="formData.isMail == 1" type="success">是</el-tag>
            <el-tag v-show="formData.isMail != 1" type="info">否</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警时间</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.alarmTime }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警内容</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.alarmContent }}
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <h4 class="mb-[5px] mt-[5px]" v-show="props.isReadonly">运行参数数据</h4>

      <div
        class="h-[260px]"
        v-if="singleDataLoading"
        v-loading="singleDataLoading"
      ></div>
      <psmParamLineChart
        v-if="!singleDataLoading && singleData"
        key="5"
        id="5"
        :showName="true"
        :seriesData="singleData"
        :nameRotate="0"
        size="small"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "DeviceAlarmSettingsedit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const singleData = ref<any>(null);
const singleDataLoading = ref<any>(false);
async function getSingleData() {
  singleData.value = null;
  singleDataLoading.value = true;
  const data: any = await request({
    url: "/dmpDosPcm/psmprocessdata/afterAndBeforeCurve",
    method: "post",
    // data: {
    //   processCode: formData.processCode,
    //   deviceId: formData.equipId,
    //   parameterName: formData.parameterName,
    //   parameterDesc: formData.parameterDesc,
    //   pointCount: "50",
    //   collectionTime: formData.alarmTime,
    // },
    data: {
      processCode: "GL",
      processId: "1851835908766720002",
      // productModel: "753428",
      deviceId: "1851835972037808132",
      processDataType: "2",
      parameterName: "M_17",
      parameterDesc: "总C补偿",
      pointCount: "25",
      collectionTime: "2025-05-06 18:31:22",
    },
  })
    .finally(() => {
      singleDataLoading.value = false;
    })
    .catch((e) => {});
  if (data) {
    singleData.value = {
      ...data.data,
      // paramName: formData.parameterDesc,
      paramName: "总C补偿",
    };
  }

  // 模拟
  // singleData.value = {};
  // setTimeout(() => {
  //   singleData.value = getSingleDataMock(50);
  //   // console.log("singleData.value", singleData.value);
  // }, 1000);
}

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  alarmTime: "",
  alarmLevel: "",
  equipId: "",
  equipName: "",
  equipCode: "",
  equipTypeId: "",
  equipTypeName: "",
  alarmId: "",
  alarmCode: "",
  alarmName: "",
  alarmContent: "",
  triggerCondition: "",
  exceptionStartTime: "",
  exceptionEndTime: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  scaAlarmSettingDetails: [],
  processEquipCode: "",
  processCode: "",
  parameterDesc: "",
  parameterName: "",
  parameterValue: "",
  alarmTriggerConditions: "",
  enabled: 1,
  isOrder: 1,
  isMail: 1,
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        alarmTime,
        alarmLevel,
        equipId,
        equipName,
        equipCode,
        equipTypeId,
        equipTypeName,
        alarmId,
        alarmCode,
        alarmName,
        alarmContent,
        triggerCondition,
        exceptionStartTime,
        exceptionEndTime,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        scaAlarmSettingDetails,
        processEquipCode,
        processCode,
        parameterDesc,
        parameterName,
        parameterValue,
        alarmTriggerConditions,
        isOrder,
        isMail,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        alarmTime,
        alarmLevel,
        equipId,
        equipName,
        equipCode,
        equipTypeId,
        equipTypeName,
        alarmId,
        alarmCode,
        alarmName,
        alarmContent,
        triggerCondition,
        exceptionStartTime,
        exceptionEndTime,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        scaAlarmSettingDetails,
        processEquipCode,
        parameterDesc,
        parameterName,
        parameterValue,
        alarmTriggerConditions,
        processCode,
        isOrder,
        isMail,
      });
      getConditionValue();
      getContentList();
      console.log(newVal);
      singleData.value = {
        ...newVal.dataTrend,
        paramName: newVal.dataTrend.name,
      };

      // getSingleData();
      // if (formData.equipId) {
      //   getCollectList();
      // }
    }
  }
);

// 采集table数据
const contentList: any = ref([]);
const getContentList = () => {
  formData.alarmContent.split("\n").forEach((item, index) => {
    contentList.value.push({
      alarmTime: formData.alarmTime,
      parameterName: item.split("-")[0],
      data: item.split("-")[1],
    });
  });

  // contentList.value.push({
  //   alarmTime: formData.alarmTime,
  //   parameter: contentList.value[0].,
  //   alarmContent: formData.alarmContent,
  // })
};

// 报警条件

// dictionaryStore.filterDictName("ScaAlarmConditions", row.conditionValue);
const conditionValue = ref([]);
const getConditionValue = () => {
  formData.scaAlarmSettingDetails.forEach((item) => {
    conditionValue.value.push(
      item.parameterName +
        dictionaryStore.filterDictName(
          "ScaAlarmConditions",
          item.conditionValue
        ) +
        item.alarmValue
    );
  });
};

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  // formRef.value.resetFields();
  // formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.alarmTime = "";
  formData.alarmLevel = "";
  formData.equipId = "";
  formData.equipName = "";
  formData.equipCode = "";
  formData.equipTypeId = "";
  formData.equipTypeName = "";
  formData.alarmId = "";
  formData.alarmCode = "";
  formData.alarmName = "";
  formData.alarmContent = "";
  formData.triggerCondition = "";
  formData.exceptionStartTime = "";
  formData.exceptionEndTime = "";
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.scaAlarmSettingDetails = [];
  contentList.value = [];
  conditionValue.value = [];
  formData.processEquipCode = "";
  formData.processCode = "";
  formData.parameterDesc = "";
  formData.parameterName = "";
  formData.parameterValue = "";
  formData.alarmTriggerConditions = "";
  formData.isOrder = 1;
  formData.isMail = 1;
}

const loading = ref(false);

/** 报警记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/iotadmin/scaalarmrecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
// ${formData.equipId}1808751001530413058
// 获取该设备的采集数据
const tableList = ref([]);
const getCollectList = async () => {
  await request({
    url: `/iotadmin/scaequipinfo/get/${formData.equipId}`,
    method: "get",
  })
    .then((res) => {
      if (res.code == 200) {
        tableList.value = res.data.scaEquipCollectionParams;
      }
    })
    .catch((error) => {});
};

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style scoped lang="scss">
h4 {
  font-weight: 600;
  color: #666;
  font-size: 15px;
  line-height: 15px;
  padding-top: 10px;
}
:deep(.el-dialog .el-dialog__body) {
  max-height: calc(100vh - 120px - 50px);
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 90px;
}
:deep(.el-descriptions__cell) {
  padding: 12px;
}
</style>
